import { defineStore } from 'pinia'
import { get, awaitTo, getLocation } from '../utils/helper.js'
const shop = defineStore({
  id: 'shop',
  state: () => ({
    isReady: null,
    onReady: null,
    info: {},
    location: {
      lat: 0,
      lng: 0
    },
    cartList: []
  }),
	
  getters: {
    shopId: state => state.info?.id ?? 0
  },
  actions: {
    async init(obj = {}) {
      let id = obj.id || 0
      
      if (!id && uni.getStorageSync('shopId')) {
        id = uni.getStorageSync('shopId')
      }
      if ((!obj.lat || !obj.lng) && (!this.location.lat || !this.location.lng)) {
        const [, locRes] = await awaitTo(getLocation())
        if (locRes) {
          this.location.lat = locRes.latitude
          this.location.lng = locRes.longitude
        }
      }
      const params = {
        shop_id: id,
        lat: obj.lat || this.location.lat,
        lon: obj.lng || this.location.lng
      }
      const { data } = await get('/Index/shop', params)
      this.info = data
      uni.setStorageSync('shopId', data.id)
      typeof this.onReady === 'function' && this.onReady()
      return Promise.resolve({ info: data })
    },
    async cartLoad() {
      const res = await get('/Store/cart', { shop_id: this.shopId })
      this.cartList = res.data
      return Promise.resolve(res.data)
    }
  }
})

export default shop
